import axios from 'axios'
import Qs from 'qs'
import getApis from './modules/'
import store from '@store'
import cache from '@cache'
import router from '../apps/admin/router'

import {
  getToken,
  removeToken,
  cacheUserinfo
} from '@cache'


let Base64 = require('js-base64').Base64
import {
  IS_LOGIN,
  SHOW_TOKEN_ERROR
} from '@store/mutation-types'


const APP_HOST = window.location.host || document.domain || 'localhost'
const API_ROOT = document.location.protocol+'//' + APP_HOST + ''
const API_ROOT_DEV = '/localapi'

axios.defaults.baseURL = (process.env.NODE_ENV === 'production' ? API_ROOT : API_ROOT_DEV)
axios.defaults.headers.Accept = 'application/json'
// Add a request interceptor
axios.interceptors.request.use(function (config) {
  config.headers['HttpHost'] = APP_HOST
  config.headers['Authorization'] = getToken()
  return config
}, function (error) {
  return Promise.reject(error)
})

//http response 拦截器
axios.interceptors.response.use(
  response => {
    if('new-token' in response.headers){
      // 更新新的token
      saveToken(response.headers['new-token'])
    }
    if (response.data.status < 0) {
      if (response.data.status === -9) { // token失效
        removeToken()
        cacheUserinfo.delete()
        store.commit(SHOW_TOKEN_ERROR, true)
        store.commit(IS_LOGIN, false)
        cache.delete('purview')
        cache.delete('nav')
      }
      if(response.data.status === -99){
        router.replace({
          path: '/member/master',
        })
      }
      let error = {
        msg: response.data.msg
      }
      return Promise.reject(error)
    }
    return response
  },
  error => {
    return Promise.reject(error)
  }
)

export default {
  axios: axios,
  purview (uri) {
    let mypurview = Base64.decode(cache.get('purview'))
    if (mypurview === '@all@') {
      return true
    }
    let path = getApis(uri).split('.')
    let purview_str = '@/' + path + '@'
    if (path.length == 1) {//判断url
      purview_str = path
    } else if (path.length == 2) {//判断接口
      purview_str = '@/' + path[1] + '@'
    }
    return mypurview.indexOf(purview_str) > -1
  },
  hget (uri, params) {
    return axios.get(getApis(uri), params).then(res => res.data)
  },
  hpost (uri, params, cancel) {
    return axios.post(getApis(uri), params, cancel).then(res => res.data)
  },
  get (uri, params) {
    return axios.get(getApis(uri), {params: params}).then(res => res.data)
  },
  post (uri, params) {
    return axios.post(getApis(uri), Qs.stringify(params)).then(res => res.data)
  },
  jget(uri, params) {
    const headerJSON = {
      "Content-Type": "application/json"
    };
    return axios.get(getApis(uri), {params: params}, {headers: headerJSON}).then(res => res.data)
  },
  jpost(uri, params) {
    const headerJSON = {
      "Content-Type": "application/json"
    }
    return axios.post(getApis(uri), JSON.stringify(params), {headers: headerJSON}).then(res => res.data)
  }
}
